package com.sangeng.exception.handler;

import com.sangeng.domain.ResponseResult;
import com.sangeng.exception.TokenParseException;
import com.sangeng.exception.UserCheckException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常捕获
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 捕获参数 验证异常
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ResponseResult<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((org.springframework.validation.FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        return new ResponseResult<>(400, "参数校验错误", errors);
    }


    @ExceptionHandler(UserCheckException.class)
    @ResponseBody
    public ResponseResult<String> handleUserCheckException(UserCheckException ex) {
        // 输出异常信息到控制台
        System.out.println("捕获到异常: " + ex.getMessage());
        // 返回响应给客户端
        return new ResponseResult<>(510, ex.getMessage());
    }

    @ExceptionHandler(TokenParseException.class)
    @ResponseBody
    public ResponseResult<String> handleTokenParseException(TokenParseException ex) {
        // 输出异常信息到控制台
        System.out.println("捕获到异常: " + ex.getMessage());
        // 返回响应给客户端
        return new ResponseResult<>(509, ex.getMessage());
    }
}
